package summary;

import java.util.LinkedList;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:13
 * https://leetcode-cn.com/problems/symmetric-tree/
 */
public class Title101 {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean isSymmetric1(TreeNode root) {
        if (root == null) {
            return true;
        }
        LinkedList<TreeNode> list = new LinkedList<>();
        list.offer(root.left);
        list.offer(root.right);
        while (!list.isEmpty()) {
            TreeNode node1 = list.poll();
            TreeNode node2 = list.poll();
            if (node1 == null && node2 == null) {
                continue;
            }else if (node1 == null || node2 == null) {
                return false;
            }else if (node1.val != node2.val) {
                return false;
            }
            list.add(node1.left);
            list.add(node2.right);
            list.add(node1.right);
            list.add(node2.left);
        }
        return true;
    }

    public boolean isSymmetric(TreeNode root) {
        return check(root.left, root.right);
    }

    private boolean check(TreeNode left, TreeNode right) {
        if (left == null && right == null) {
            return true;
        } else if (left == null || right == null) {
            return false;
        }
        if (left.val != right.val) {
            return false;
        }
        return check(left.left, right.right) && check(left.right, right.left);
    }


    public boolean isSymmetric2(TreeNode root) {
        if (root == null) {
            return true;
        }
        return check2(root.left, root.right);
    }

    private boolean check2(TreeNode left, TreeNode right) {
        if (left == null && right == null) {
            return true;
        } else if (left == null || right == null) {
            return false;
        } else if (left.val != right.val) {
            return false;
        }
        return check2(left.left, right.right) && check2(left.right, right.left);
    }


    public static void main(String[] args) {

    }
}
